package com.css.bjdt_core.importExport.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.ObjectInputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.css.bjdt_core.importExport.entity.DnDzzIE;
import com.css.bjdt_core.importExport.entity.MsgCenter;
import com.css.bjdt_core.importExport.entity.RptBatchDzzRelIE;
import com.css.bjdt_core.importExport.entity.RptBatchIE;
import com.css.bjdt_core.importExport.entity.RptBatchTemplateRelIE;
import com.css.bjdt_core.importExport.entity.RptBatchUnitRelIE;
import com.css.bjdt_core.importExport.entity.RptUnitAnnualRelIE;
import com.css.bjdt_core.importExport.entity.RptUnitIE;
import com.css.bjdt_core.importExport.entity.WrapObject;
import com.css.bjdt_core.reportPrepare.entity.RptUnitAnnualRel;
import com.css.bjdt_core.util.FileUtils;
import com.css.bjdt_core.util.ReportConstant;

@Service
public class DataImportService {

	@Autowired
	private Dao dao;

	public String importReport(String filePath, final String dzzIdSession, final String unitId, final String annualId) {
		// 判断文件是否存在
		File file = new File(filePath);
		if (!file.exists()) {
			return "文件不存在，请正确选择。";
		}

		// 消息
		final MsgCenter msgCenter = new MsgCenter();
		try {
			// 读取文件内容
			byte[] fileData = FileUtils.readBytesFromFile(new File(filePath));

			// DES解密
			//byte[] decArray = new DESUtil().decrypt(fileData);

			// ZIP解压缩
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ByteArrayInputStream in = new ByteArrayInputStream(fileData);
			GZIPInputStream gunzip = new GZIPInputStream(in);
			byte[] buffer = new byte[256];
			int n;
			while ((n = gunzip.read(buffer)) >= 0) {
				out.write(buffer, 0, n);
			}

			// 反序列化
			ByteArrayInputStream bais = new ByteArrayInputStream(out.toByteArray());
			ObjectInputStream ois = new ObjectInputStream(bais);
			final WrapObject wrap = (WrapObject) ois.readObject();
			ois.close();
			msgCenter.putMsg("文件读入完毕。");

			// 开事务
			Trans.exec(new Atom() {
				public void run() {
					String dzzId = wrap.getDzzId();
					RptUnitIE rptUnitIE = wrap.getRptUnitIE();
					RptBatchIE rptBatchIE = wrap.getRptBatchIE();
					RptBatchUnitRelIE rptBatchUnitRelIE = wrap.getRptBatchUnitRelIE();
					DnDzzIE dnDzzIE = wrap.getDnDzzIE();
					RptUnitAnnualRelIE rptUnitAnnualRelIE = wrap.getRptUnitAnnualRelIE();
					RptBatchDzzRelIE rptBatchDzzRelIE = wrap.getRptBatchDzzRelIE();
					RptBatchTemplateRelIE rptBatchTemplateRelIE = wrap.getRptBatchTemplateRelIE();
					//先清历史记录
					deleteDzzExportData(rptBatchIE.getId(), dzzId, annualId, rptUnitIE.getId());

					//开始做单表的Insert处理
					rptUnitIE.setPid(unitId);
					dao.insert(rptUnitIE);
					dnDzzIE.setSjdzzid(dzzIdSession);
					dao.insert(dnDzzIE);
					dao.insert(rptBatchIE);
					dao.insert(rptBatchUnitRelIE);
					dao.insert(rptUnitAnnualRelIE);
					dao.insert(rptBatchDzzRelIE);
					dao.insert(rptBatchTemplateRelIE);

					// --------------无特殊处理的表-------------------
					Map<String, List<Record>> dataMap = wrap.getDataMap();
					for (String name : dataMap.keySet()) {
						List<Record> dataList = dataMap.get(name);
						if (dataList.size() == 0) {
							msgCenter.putMsg("[" + name + "]共有0条数据。");
							continue;
						}

						// 列名
						Set<String> columnList = dataList.get(0).getColumnNames();

						// 构建insert语句
						StringBuilder sqlBuilder = new StringBuilder();
						sqlBuilder.append("insert into ");
						sqlBuilder.append(name);
						sqlBuilder.append("(");

						// 字段列表
						for (String column : columnList) {
							sqlBuilder.append(column);
							sqlBuilder.append(",");
						}
						sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
						sqlBuilder.append(") values(");

						// 值列表
						for (String column : columnList) {
							sqlBuilder.append("@");
							sqlBuilder.append(column);
							sqlBuilder.append(",");
						}
						sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
						sqlBuilder.append(")");

						// 追加batch
						Sql sql = Sqls.create(sqlBuilder.toString());
						for (Record record : dataList) {
							for (String column : columnList) {
								sql.params().set(column, record.get(column));
							}
							sql.addBatch();
						}
						dao.execute(sql);

						msgCenter.putMsg("[" + name + "]共有" + dataList.size() + "条数据。");
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	//删除这个单位原先表里的所有数据
	public void deleteDzzExportData(final String batchId, final String dzzId, final String annualId,
			final String unitId) {
		// 开事务
		Trans.exec(new Atom() {
			public void run() {
				//先删指标值的表
				String tableName = ReportConstant.EXECUTIVE_TABLE_PREFIX + annualId;
				Sql strSql = Sqls.create("delete from " + tableName + " where DZZ_ID = @dzzId");
				strSql.params().set("dzzId", dzzId);
				dao.execute(strSql);
				//再删单位信息
				dao.clear(RptUnitIE.class, Cnd.where("id", "=", unitId));
				//再删批次和单位的关系
				//dao.clear(RptBatchUnitRelIE.class, Cnd.where("BATCH_ID", "=", batchId));
				//再删批次和报表的关系
				dao.clear(RptBatchTemplateRelIE.class, Cnd.where("BATCH_ID", "=", batchId));
				//再删批次信息
				dao.clear(RptBatchIE.class, Cnd.where("BATCH_ID", "=", batchId));
				//再删党组织信息
				dao.clear(DnDzzIE.class, Cnd.where("DZZID", "=", dzzId));
				//删单位和年度之间的关系
				dao.clear(RptUnitAnnualRel.class,
						Cnd.where("UNIT_ID", "=", unitId).and("ANNUAL_ID", "=", annualId).and("DZZ_ID", "=", dzzId));
			}
		});

	}
}
